package sparsearray;

/**
 * 稀疏数组
 */
public class SparseArray {

    public static void main(String[] args) {

        //11*11二维数组
        int[][] chessArray1 = new int[12][12];
        chessArray1[1][2] =1;
        chessArray1[2][3]=2;
        chessArray1[3][4]=2;
        int sum =0;
        for (int[] row :chessArray1){
            for (int data:row){
                System.out.printf("%d\t",data);
                if (data!=0){
                    sum++;//获取二维数组的有效数据个数
                }
            }
            System.out.println();
        }

        System.out.println("-----------------------------------");

        //创建稀疏数组
        int[][] sparseArray1 = new int[sum + 1][3];
        sparseArray1[0][0]=chessArray1.length;
        sparseArray1[0][1]=chessArray1[0].length;
        sparseArray1[0][2]=sum;

        //给稀疏数组赋值
        int count = 0;
        for (int i = 0; i < chessArray1.length; i++) {
            for (int j = 0; j <chessArray1[0].length ; j++){
                if (chessArray1[i][j]!=0){
                    count++;
                    sparseArray1[count][0]=i;
                    sparseArray1[count][1]=j;
                    sparseArray1[count][2]=chessArray1[i][j];
                }
            }
        }

        for (int[] row : sparseArray1) {
            for (int data : row) {
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }

        System.out.println("----------------------------------");

        //将稀疏数组还原为二维数组
        int[][] chessArray2=new int[sparseArray1[0][0]][sparseArray1[0][1]];
        for (int i = 1; i <= sparseArray1[0][2]; i++) {

            int row=sparseArray1[i][0];
            int column=sparseArray1[i][1];
            chessArray2[row][column]=sparseArray1[i][2];
        }

        for (int row[]: chessArray2){
            for (int data: row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }

    }
}
